<template>
  <div class="user-admin">
    <a-input-search
    shape="round"
      v-model:value="keyword"
      placeholder="输入用户名搜索"
       enter-button="搜索"
      style="width: 200px"
      @search="onSearch"
    />
    <a-button
      type="primary"
      @click="openModal({})"
      style="margin-right: 2px"
      >新增</a-button
    >
    <a-button
      type="primary"
      @click="openExcelModal"
      style="margin-right: 2px"
      >导入</a-button
    >
    <a-table :dataSource="dataSource"  :loading="loading" :columns="columns" size="small" style="margin-top: 5px;">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key == 'action'">
          <a-button
            type="primary"
            shape="round"
            @click="openModal(record)"
            style="margin-right: 10px"
            size="small"
            >修改</a-button
          >
          &nbsp;
          <a-button type="primary" shape="round" size="small" @click="openChangePwdModal(record)"  style="margin-right: 10px">
              更改密码
          </a-button>
          &nbsp;
          <a-button type="primary" danger shape="round" size="small">
            <a-popconfirm :title="`确认[ ${record.userName} ]删除吗？`"  @confirm="deleteUser(record.id)" okText="删除" cancelText="取消">
              <template #icon><question-circle-outlined style="color: red"/></template>
              删除
            </a-popconfirm>
          </a-button>
        
        </template>
        <template v-if="column.key == 'isAble'">
          <a-switch :checked="record.isAble==0 ? true : false" disabled @change="isAbleChange" />
          <!-- 不用开开关，直接显示 -->
          <!-- {{record.isAble==0 ? '可用' : '禁用'}} -->
        </template>
      </template>
    </a-table>
    <!-- 模态框 -->
    <a-modal
      v-model:visible="visible"
      title="新增用户"
      @ok="addNewUserOrUpdateUserInfo"
      @cancel="cancelAddUser"
      :okText="formState.id ? '保存' : '添加'"
      cancelText="取消">
      <a-form
        :model="formState"
        name="nest-messages"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item
          name="userName"
          label="用户名"
          :rules="[{ required: true }]"
        >
          <a-input v-model:value="formState.userName" />
        </a-form-item>
      <!-- 新增用户才进行填写密码 -->
        <a-form-item v-if="!formState.id" name="password" label="密码" :rules="[{ required: true }]">
          <a-input type="password" v-model:value="formState.password" />
        </a-form-item>

        <a-form-item name="nickName" label="昵称">
          <a-input v-model:value="formState.nickName" />
        </a-form-item>
        <a-form-item name="permission" label="权限">
          <a-radio-group v-model:value="formState.permission" name="permission">
            <a-radio :value="1">普通用户</a-radio>
            <a-radio :value="0">超级管理员</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item name="isAble" v-model:value="formState.isAble" label="是否可用">
          <a-radio-group v-model:value="formState.isAble" name="isAble">
            <a-radio :value="0" >可用</a-radio>
            <a-radio :value="1">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
     <a-modal
      v-model:visible="pwdModalIsOPen"
      title="更改密码"
      @ok="reUpdatePassowrd"
      @cancel="cancelRePassword"
      :confirm-loading="loading"
      okText="修改"
      cancelText="取消">
      <a-form
        :model="rePasswordForm"
        name="nest-messages"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item  name="password" label="新密码" :rules="[{ required: true }]">
          <a-input type="password" v-model:value="rePasswordForm.password" />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
    v-model:visible="excelOpen"
    title="导入用户"
    @ok="okImportUsers"
    @cancel="cancelImport"
    :confirm-loading="loading"
    okText="导入"
    cancelText="取消">
    <a-upload
        v-model:file-list="fileList"
        name="file"
        :progress="progress"
        @change="handleChange"
        :customRequest="customRequest"
      >
        <a-button>
          <upload-outlined></upload-outlined>
          请上传文件
        </a-button>
      </a-upload>
    <div>
      <br>  
      <a :href="baseUrl+'/import/template'" style="">
      下载模板Excel模板
      </a>
      <br>
      <span style="color: red;"> 提示：仅允许导入“xls”或“xlsx”格式文件！</span>
    </div>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { ref, onMounted, computed, reactive } from "vue";
import { reqGetAllUser, reqAddNewUser,reqDeleteUserById,reqUpdateUserPassword,reqImportUsers } from "../../apis";
import { message } from "ant-design-vue";
import { QuestionCircleOutlined,UploadOutlined } from "@ant-design/icons-vue";
declare let process:any;
// 密码的那一栏不显示，因为是加密过的。
let columns = [
  {
    title: "用户名",
    dataIndex: "userName",
    key: "userName",
  },
  {
    title: "昵称",
    dataIndex: "nickName",
    key: "nickName",
  },
  {
    title: "用户权限",
    dataIndex: "permission",
    key: "permission",
    responsive: ['lg'],
  },
  {
    title: "是否可用",
    dataIndex: "isAble",
    key: "isAble",
    responsive: ['lg'],
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
  },
];
export default {
  name: "UserAdmin",
  components: {
    QuestionCircleOutlined,
    UploadOutlined
  },
  setup() {
    let baseUrl =  process.env.VUE_APP_SERVER;
    let isAble = ref(true);
    let dataSource = ref();
    // 搜索关键词
    let keyword = ref('');
    // 加载效果
    let loading = ref(false);
    let visible = ref(false);
    let excelOpen = ref(false);
    let pwdModalIsOPen = ref(false);
    let formState = ref();
    let file = reactive({});
    let rePasswordForm = reactive({
      id:'',
      password: ''
    });
    formState.value = {};
    // 模糊查询
    async function getAllUserInfo(user:any) {
      loading.value = true;
      const res = await reqGetAllUser(user);
      if (res.data.success) {
        dataSource.value = res.data.content;
      loading.value = false;

      }else {
        message.error("获取失败")
      loading.value = false;

      } 
    }
    function openModal(record:any) {
        if(record.id){
            // console.log(123);
            const deepCopyRecord = JSON.parse(JSON.stringify(record));
            formState.value = deepCopyRecord;
        }
      visible.value = true;
    }
    // 添加用户
    async function addNewUserOrUpdateUserInfo() {
      const res = await reqAddNewUser(formState.value);
      if (res.data.success) {
        message.success(res.data.message);
        // 重新获取数据
        getAllUserInfo({});
      } else {
        message.error(res.data.message);
      }
      visible.value = false;
      formState.value = {};
    //   console.log(formState.value);
    }
    // 取消添加用户
    function cancelAddUser(){
    //    清空表单
        formState.value = {};
    }
    // 是否可用
    function isAbleChange() {
      console.log(11);
    }
    // 删除用户
    async function deleteUser(id:any) {
        const res = await reqDeleteUserById(id);
        if(res.data.success){
            message.success("删除成功");
            getAllUserInfo({userName:keyword.value});
        }else {
            message.error(res.data.message);
        }
    }
    function onSearch(){
      getAllUserInfo({userName:keyword.value});
    }
    // 修改密码
    function openChangePwdModal(record:any){
      pwdModalIsOPen.value = true;
      // 初始化操作
      rePasswordForm.id = record.id;
      rePasswordForm.password = '';
    }
    async function reUpdatePassowrd(){
      loading.value = true;
      let res = await reqUpdateUserPassword(rePasswordForm.id, rePasswordForm.password);
      if(res.data.success){
        loading.value = false;
        pwdModalIsOPen.value = false;
        message.success(res.data.message);
      }else {
        loading.value = false;
        message.error("密码修改失败")
      }
    }
    function cancelRePassword(){
      rePasswordForm.id = '';
      rePasswordForm.password = '';
    }
    function openExcelModal(){
      excelOpen.value = true;
      
    }
    function okImportUsers(){
      console.log('导入');
      console.log(file);
      excelOpen.value = false;
    }
    function cancelImport(){
      console.log('取消导入');
      
    }
    function customRequest(data:any){
      const formData = new FormData();
      formData.append('file',data.file);
      console.log(formData);
      reqImportUsers(formData).then(res => {
        console.log(res);
      })
      
    }
    // 生命周期钩子
    onMounted(() => {
      getAllUserInfo({userName:keyword.value});
    });
    return {
      dataSource,
      columns,
      visible,
      //   模态框
      openModal,
      formState,
      addNewUserOrUpdateUserInfo,
      cancelAddUser,
      isAble,
      isAbleChange,
      // 搜索
      onSearch,
      keyword,
      loading,
    //   删除用户
    deleteUser,
    // 修改密码
    openChangePwdModal,
    pwdModalIsOPen,
    rePasswordForm,
    reUpdatePassowrd,
    cancelRePassword,
    // 导入导出
    openExcelModal,
    excelOpen,
    okImportUsers,
    cancelImport,
    baseUrl,
    customRequest
    };
  },
};
</script>

<style>
</style>